Skip to content

fix(proxy)!: count prompt-only token_counter requests with the provider when call_endpoint is set - #46839

Merged
mateo-berri merged 10 commits into
mainfrom
litellm_fix_token_counter_prompt_only_provider_count
Oct 16, 2026
Merged

mateo-berri merged 10 commits into
mainfrom
litellm_fix_token_counter_prompt_only_provider_count

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • /utils/token_counter?call_endpoint=true dropped prompt before calling Gemini's count API
  • Gemini deployments then answered a fixed count for any prompt (AI Studio 32, Vertex 1)
  • A prompt next to messages answered 500 locally, and with call_endpoint=true it was dropped with no error

How it solves it:

  • On Gemini and Vertex AI, a prompt-only request reaches the count API as one user message
  • Other providers keep their local count for a prompt-only request
  • An empty messages or contents list counts as not sent
  • On the local count, a prompt next to system or tools is counted as a user message with them

Breaking change

Sending prompt with a non-empty messages or contents now answers 400. Callers should remove prompt, or set drop_params to count only the conversation

User Flow

Before: a team that sizes prompts with the gateway's token counter gets one fixed number for every prompt on a Gemini deployment

  1. They send POST https://litellm-domain/utils/token_counter?call_endpoint=true with {"model": "<gemini deployment>", "prompt": "<about 2,000 tokens of text>"}
  2. The response comes back 200 with "total_tokens": 32 on a Google AI Studio deployment, or 1 on a Vertex AI one
  3. A one-word prompt like "hi" gets that same number
  4. Only resending the text as "messages": [{"role": "user", "content": "..."}] gives the real count, 2032 or 2001

After: the same prompt-only request comes back with Google's own count for that text

  1. They send POST https://litellm-domain/utils/token_counter?call_endpoint=true with {"model": "<gemini deployment>", "prompt": "<about 2,000 tokens of text>"}
  2. The response comes back 200 with "total_tokens": 2032 on Google AI Studio, or 2001 on Vertex AI
  3. The prompt and messages forms of the same text now return the same count
Design decisions

Scope. Only Gemini and Vertex AI deployments get the prompt as a user message, because only their count APIs were already called for a prompt-only request, and they counted an empty request (AI Studio 32, Vertex 1, Vertex Claude a 400). The Anthropic, Bedrock, OpenAI, and Azure AI counters skip the call when there are no messages, so the local tokenizer answers there, as before. The first version of this PR sent the prompt to every provider. Review showed that adds a provider round trip to requests that never waited on one, so a stalled count endpoint hangs them, and it needed a local fallback that hid Gemini provider errors behind a 200. Sending prompts to those other count APIs is left for its own change

Provider failure on a prompt-only request. On Gemini and Vertex AI a failed provider count answers with the provider's error, as it did before for a prompt-only request and as the messages form does. No new fallback is added

Empty prompt. "prompt": "" has nothing to count, so no user message is built and the request behaves exactly as it does today

Prompt next to messages or contents. prompt is an alternative to messages and contents, the same contract as litellm.token_counter. The repo's drop_params rule decides the mix: without it the request answers 400 naming prompt, and with it the prompt is dropped and the conversation counted. Before, the provider path dropped the prompt with no error and the local count answered 500. Counting both was rejected because it invents a meaning and can send two user turns in a row. An empty list counts as not sent, so the prompt is counted. With drop_params, a prompt next to contents on the local count still counts the prompt, as at the merge base, since that path cannot read contents

Prompt next to system or tools. On the local count, a prompt with system or tools is counted as one user message with them, matching the messages form and the Gemini path. A plain prompt is still counted as text, so its count does not change

Message shape. The prompt goes as {"role": "user", "content": prompt}, the same shape a caller sends in messages, so both forms of one text get the same count

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Last updated: aac4a81. QA ran on 2703897, the last commit with a product diff, and /live-pr-risk on 3e8d052

Both legs boot one config with 2 uvicorn workers and call the real provider count APIs. Before ran at the merge base cb7e6a7 and After at 2703897. long.txt is "The quick brown fox jumps over the lazy dog. " repeated 200 times

Config and boot command
model_list:
  - model_name: litellm-qa-tc-aistudio
    litellm_params:
      model: gemini/gemini-4-argon
      api_key: os.environ/GEMINI_API_KEY
  - model_name: litellm-qa-tc-aistudio-invalid-key
    litellm_params:
      model: gemini/gemini-4-argon
      api_key: not-a-real-gemini-key
  - model_name: litellm-qa-tc-aistudio-drop-params
    litellm_params:
      model: gemini/gemini-4-argon
      api_key: os.environ/GEMINI_API_KEY
      drop_params: true
  - model_name: litellm-qa-tc-vertex
    litellm_params:
      model: vertex_ai/gemini-4-argon
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
  - model_name: litellm-qa-tc-anthropic
    litellm_params:
      model: anthropic/claude-opus-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: litellm-qa-tc-openai
    litellm_params:
      model: openai/gpt-5.6
      api_key: os.environ/OPENAI_API_KEY
  - model_name: litellm-qa-tc-bedrock
    litellm_params:
      model: bedrock/global.anthropic.claude-opus-5-5
      aws_region_name: us-east-1
  - model_name: litellm-qa-tc-bedrock-unserved-region
    litellm_params:
      model: bedrock/global.anthropic.claude-opus-5-5
      aws_region_name: us-west-2
  - model_name: litellm-qa-tc-vertex-claude
    litellm_params:
      model: vertex_ai/claude-opus-5-5
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
python litellm/proxy/proxy_cli.py --config config.yaml --port $PORT --num_workers 2
Request Before After Same text as a message
AI Studio, long prompt 32 2032 2032
Vertex AI, long prompt 1 2001 2001
AI Studio, "hi" next to messages 2032 400 error n/a
AI Studio, prompt next to empty messages 32 2032 n/a
AI Studio local, "hi" next to messages internal server error 400 error n/a
drop_params, "hi" next to messages 2032 2032 n/a
drop_params local, "hi" next to messages internal server error 2016 n/a
AI Studio local, prompt next to system 2009 4029 4029
AI Studio local, prompt next to a tool 2009 2056 2056
The other 16 cases
Request Before After Same text as a message
Vertex Claude, long prompt 400 error 3608 3608
Anthropic, long prompt 2001 2001 3608
Bedrock, long prompt 2009 2009 3608
OpenAI, long prompt 2009 2009 2007
Bedrock, region without the model 2009 2009 404 error
AI Studio, invalid key 400 error 400 error 400 error
AI Studio, "hi" 32 32 n/a
AI Studio, empty prompt 32 32 n/a
AI Studio, long prompt next to system 43 2043 n/a
Vertex AI, prompt next to empty messages 1 2001 n/a
AI Studio, prompt next to empty contents 400 error 2032 n/a
Anthropic, prompt next to empty messages internal server error 2001 n/a
AI Studio local, prompt next to empty messages internal server error 2009 n/a
AI Studio, "hi" next to contents 2032 400 error n/a
AI Studio local, "hi" next to contents 1 400 error n/a
AI Studio, call_endpoint=false 2009 2009 n/a

Other things the run showed

  • The local tokenizer counts Claude about 45% low, unchanged here

Before (cb7e6a7)

AI Studio long prompt

  1. AI Studio, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p}')"
    {"total_tokens":32,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":32,"promptTokensDetails":[{"modality":"TEXT","tokenCount":32}]},"error":false,"error_message":null,"status_code":null}
    
The other 9 cases

Vertex AI long prompt

2 requests
  1. Vertex AI Gemini, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-vertex",prompt:$p}')"
    {"total_tokens":1,"request_model":"litellm-qa-tc-vertex","model_used":"gemini-4-argon","tokenizer_type":"gemini","original_response":{"totalTokens":1,"promptTokensDetails":[{"modality":"TEXT","tokenCount":1}]},"error":false,"error_message":null,"status_code":null}
    
  2. Vertex Claude, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-vertex-claude",prompt:$p}')"
    {"error":{"message":"{\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"messages: at least one message is required\"},\"request_id\":\"req_vrtx_011Cg5QTP73k1XeynD73YyHS\"}","type":"token_counting_error","param":"model","code":"400"}}
    

Other providers keep the local count

4 requests
  1. Anthropic, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-anthropic",prompt:$p}')"
    {"total_tokens":2001,"request_model":"litellm-qa-tc-anthropic","model_used":"claude-opus-5-5","tokenizer_type":"huggingface_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  2. Bedrock, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-bedrock",prompt:$p}')"
    {"total_tokens":2009,"request_model":"litellm-qa-tc-bedrock","model_used":"global.anthropic.claude-opus-5-5","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  3. OpenAI, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-openai",prompt:$p}')"
    {"total_tokens":2009,"request_model":"litellm-qa-tc-openai","model_used":"gpt-5.6","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  4. Bedrock in a region without the model, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-bedrock-unserved-region",prompt:$p}')"
    {"total_tokens":2009,"request_model":"litellm-qa-tc-bedrock-unserved-region","model_used":"global.anthropic.claude-opus-5-5","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    

Same text as a message

7 requests
  1. AI Studio

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":2032,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":2032,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2032}]},"error":false,"error_message":null,"status_code":null}
    
  2. Vertex AI

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-vertex",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":2001,"request_model":"litellm-qa-tc-vertex","model_used":"gemini-4-argon","tokenizer_type":"gemini","original_response":{"totalTokens":2001,"totalBillableCharacters":7200,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2001}]},"error":false,"error_message":null,"status_code":null}
    
  3. Vertex Claude

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-vertex-claude",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":3608,"request_model":"litellm-qa-tc-vertex-claude","model_used":"claude-opus-5-5","tokenizer_type":"vertex_ai_partner_models","original_response":{"input_tokens":3608,"tokenizer_used":"vertex_ai_partner_models"},"error":false,"error_message":null,"status_code":null}
    
  4. Anthropic

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-anthropic",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":3608,"request_model":"litellm-qa-tc-anthropic","model_used":"claude-opus-5-5","tokenizer_type":"anthropic_api","original_response":{"input_tokens":3608},"error":false,"error_message":null,"status_code":null}
    
  5. Bedrock

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-bedrock",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":3608,"request_model":"litellm-qa-tc-bedrock","model_used":"global.anthropic.claude-opus-5-5","tokenizer_type":"bedrock_mantle_api","original_response":{"input_tokens":3608},"error":false,"error_message":null,"status_code":null}
    
  6. OpenAI

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-openai",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":2007,"request_model":"litellm-qa-tc-openai","model_used":"gpt-5.6","tokenizer_type":"openai_api","original_response":{"object":"response.input_tokens","input_tokens":2007},"error":false,"error_message":null,"status_code":null}
    
  7. Bedrock in a region without the model

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-bedrock-unserved-region",messages:[{role:"user",content:$p}]}')"
    {"error":{"message":"{\"type\":\"error\",\"request_id\":\"req_alaeg7kmkcr6gduv4hmoniodzlcq2gj37gnxcuh5yprua4b6gqva\",\"error\":{\"type\":\"not_found_error\",\"message\":\"The model 'anthropic.claude-opus-5-5' does not exist\"}}","type":"token_counting_error","param":"model","code":"404"}}
    

Gemini provider error

2 requests
  1. AI Studio with an invalid key, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio-invalid-key",prompt:$p}')"
    {"error":{"message":"litellm.APIError: Google Gen AI Studio API error: 400 - {\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"API key not valid. Please pass a valid API key.\",\n    \"status\": \"INVALID_ARGUMENT\",\n    \"details\": [\n      {\n        \"@type\": \"type.googleapis.com/google.rpc.ErrorInfo\",\n        \"reason\": \"API_KEY_INVALID\",\n        \"domain\": \"googleapis.com\",\n        \"metadata\": {\n          \"service\": \"generativelanguage.googleapis.com\"\n        }\n      },\n      {\n        \"@type\": \"type.googleapis.com/google.rpc.LocalizedMessage\",\n        \"locale\": \"en-US\",\n        \"message\": \"API key not valid. Please pass a valid API key.\"\n      }\n    ]\n  }\n}\n","type":"token_counting_error","param":"model","code":"400"}}
    
  2. AI Studio with an invalid key, same text as a message

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio-invalid-key",messages:[{role:"user",content:$p}]}')"
    {"error":{"message":"litellm.APIError: Google Gen AI Studio API error: 400 - {\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"API key not valid. Please pass a valid API key.\",\n    \"status\": \"INVALID_ARGUMENT\",\n    \"details\": [\n      {\n        \"@type\": \"type.googleapis.com/google.rpc.ErrorInfo\",\n        \"reason\": \"API_KEY_INVALID\",\n        \"domain\": \"googleapis.com\",\n        \"metadata\": {\n          \"service\": \"generativelanguage.googleapis.com\"\n        }\n      },\n      {\n        \"@type\": \"type.googleapis.com/google.rpc.LocalizedMessage\",\n        \"locale\": \"en-US\",\n        \"message\": \"API key not valid. Please pass a valid API key.\"\n      }\n    ]\n  }\n}\n","type":"token_counting_error","param":"model","code":"400"}}
    

Short and empty prompts

4 requests
  1. AI Studio, prompt "hi"

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:"hi"}')"
    {"total_tokens":32,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":32,"promptTokensDetails":[{"modality":"TEXT","tokenCount":32}]},"error":false,"error_message":null,"status_code":null}
    
  2. Vertex AI, prompt "hi"

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-vertex",prompt:"hi"}')"
    {"total_tokens":1,"request_model":"litellm-qa-tc-vertex","model_used":"gemini-4-argon","tokenizer_type":"gemini","original_response":{"totalTokens":1,"promptTokensDetails":[{"modality":"TEXT","tokenCount":1}]},"error":false,"error_message":null,"status_code":null}
    
  3. AI Studio, empty prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:""}')"
    {"total_tokens":32,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":32,"promptTokensDetails":[{"modality":"TEXT","tokenCount":32}]},"error":false,"error_message":null,"status_code":null}
    
  4. Anthropic, empty prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-anthropic",prompt:""}')"
    {"total_tokens":0,"request_model":"litellm-qa-tc-anthropic","model_used":"claude-opus-5-5","tokenizer_type":"huggingface_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    

Prompt next to a conversation

6 requests
  1. AI Studio, "hi" next to long messages

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:"hi",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":2032,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":2032,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2032}]},"error":false,"error_message":null,"status_code":null}
    
  2. AI Studio, "hi" next to long messages, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:"hi",messages:[{role:"user",content:$p}]}')"
    {"error":{"message":"Internal server error","type":"internal_server_error"}}
    
  3. AI Studio, "hi" next to long contents

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:"hi",contents:[{role:"user",parts:[{text:$p}]}]}')"
    {"total_tokens":2032,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":2032,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2032}]},"error":false,"error_message":null,"status_code":null}
    
  4. AI Studio, "hi" next to long contents, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:"hi",contents:[{role:"user",parts:[{text:$p}]}]}')"
    {"total_tokens":1,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  5. AI Studio with drop_params, "hi" next to long messages

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio-drop-params",prompt:"hi",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":2032,"request_model":"litellm-qa-tc-aistudio-drop-params","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":2032,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2032}]},"error":false,"error_message":null,"status_code":null}
    
  6. AI Studio with drop_params, "hi" next to long messages, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio-drop-params",prompt:"hi",messages:[{role:"user",content:$p}]}')"
    {"error":{"message":"Internal server error","type":"internal_server_error"}}
    

Prompt next to system or tools

5 requests
  1. AI Studio, long prompt next to a short system

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p,system:"You are a helpful assistant."}')"
    {"total_tokens":43,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":43,"promptTokensDetails":[{"modality":"TEXT","tokenCount":43}]},"error":false,"error_message":null,"status_code":null}
    
  2. AI Studio, long prompt next to a long system, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p,system:$p}')"
    {"total_tokens":2009,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  3. AI Studio, same text as a message next to that system, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",messages:[{role:"user",content:$p}],system:$p}')"
    {"total_tokens":4029,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  4. AI Studio, long prompt next to a tool, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p,tools:[{type:"function",function:{name:"get_weather",description:"Get the current weather for a city",parameters:{type:"object",properties:{city:{type:"string"}},required:["city"]}}}]}')"
    {"total_tokens":2009,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  5. AI Studio, same text as a message next to that tool, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",messages:[{role:"user",content:$p}],tools:[{type:"function",function:{name:"get_weather",description:"Get the current weather for a city",parameters:{type:"object",properties:{city:{type:"string"}},required:["city"]}}}]}')"
    {"total_tokens":2056,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    

Prompt next to an empty list

5 requests
  1. AI Studio, long prompt next to empty messages

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p,messages:[]}')"
    {"total_tokens":32,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":32,"promptTokensDetails":[{"modality":"TEXT","tokenCount":32}]},"error":false,"error_message":null,"status_code":null}
    
  2. Vertex AI, long prompt next to empty messages

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-vertex",prompt:$p,messages:[]}')"
    {"total_tokens":1,"request_model":"litellm-qa-tc-vertex","model_used":"gemini-4-argon","tokenizer_type":"gemini","original_response":{"totalTokens":1,"promptTokensDetails":[{"modality":"TEXT","tokenCount":1}]},"error":false,"error_message":null,"status_code":null}
    
  3. AI Studio, long prompt next to empty contents

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p,contents:[]}')"
    {"error":{"message":"litellm.APIError: Google Gen AI Studio API error: 400 - {\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"CountTokens requires generate_content_request or contents to be set.\",\n    \"status\": \"INVALID_ARGUMENT\"\n  }\n}\n","type":"token_counting_error","param":"model","code":"400"}}
    
  4. Anthropic, long prompt next to empty messages

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-anthropic",prompt:$p,messages:[]}')"
    {"error":{"message":"Internal server error","type":"internal_server_error"}}
    
  5. AI Studio, long prompt next to empty messages, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p,messages:[]}')"
    {"error":{"message":"Internal server error","type":"internal_server_error"}}
    

Without call_endpoint

1 request
  1. AI Studio, long prompt, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p}')"
    {"total_tokens":2009,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    

After (2703897)

AI Studio long prompt

  1. AI Studio, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p}')"
    {"total_tokens":2032,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":2032,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2032}]},"error":false,"error_message":null,"status_code":null}
    
The other 9 cases

Vertex AI long prompt

2 requests
  1. Vertex AI Gemini, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-vertex",prompt:$p}')"
    {"total_tokens":2001,"request_model":"litellm-qa-tc-vertex","model_used":"gemini-4-argon","tokenizer_type":"gemini","original_response":{"totalTokens":2001,"totalBillableCharacters":7200,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2001}]},"error":false,"error_message":null,"status_code":null}
    
  2. Vertex Claude, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-vertex-claude",prompt:$p}')"
    {"total_tokens":3608,"request_model":"litellm-qa-tc-vertex-claude","model_used":"claude-opus-5-5","tokenizer_type":"vertex_ai_partner_models","original_response":{"input_tokens":3608,"tokenizer_used":"vertex_ai_partner_models"},"error":false,"error_message":null,"status_code":null}
    

Other providers keep the local count

4 requests
  1. Anthropic, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-anthropic",prompt:$p}')"
    {"total_tokens":2001,"request_model":"litellm-qa-tc-anthropic","model_used":"claude-opus-5-5","tokenizer_type":"huggingface_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  2. Bedrock, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-bedrock",prompt:$p}')"
    {"total_tokens":2009,"request_model":"litellm-qa-tc-bedrock","model_used":"global.anthropic.claude-opus-5-5","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  3. OpenAI, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-openai",prompt:$p}')"
    {"total_tokens":2009,"request_model":"litellm-qa-tc-openai","model_used":"gpt-5.6","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  4. Bedrock in a region without the model, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-bedrock-unserved-region",prompt:$p}')"
    {"total_tokens":2009,"request_model":"litellm-qa-tc-bedrock-unserved-region","model_used":"global.anthropic.claude-opus-5-5","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    

Same text as a message

7 requests
  1. AI Studio

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":2032,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":2032,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2032}]},"error":false,"error_message":null,"status_code":null}
    
  2. Vertex AI

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-vertex",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":2001,"request_model":"litellm-qa-tc-vertex","model_used":"gemini-4-argon","tokenizer_type":"gemini","original_response":{"totalTokens":2001,"totalBillableCharacters":7200,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2001}]},"error":false,"error_message":null,"status_code":null}
    
  3. Vertex Claude

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-vertex-claude",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":3608,"request_model":"litellm-qa-tc-vertex-claude","model_used":"claude-opus-5-5","tokenizer_type":"vertex_ai_partner_models","original_response":{"input_tokens":3608,"tokenizer_used":"vertex_ai_partner_models"},"error":false,"error_message":null,"status_code":null}
    
  4. Anthropic

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-anthropic",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":3608,"request_model":"litellm-qa-tc-anthropic","model_used":"claude-opus-5-5","tokenizer_type":"anthropic_api","original_response":{"input_tokens":3608},"error":false,"error_message":null,"status_code":null}
    
  5. Bedrock

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-bedrock",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":3608,"request_model":"litellm-qa-tc-bedrock","model_used":"global.anthropic.claude-opus-5-5","tokenizer_type":"bedrock_mantle_api","original_response":{"input_tokens":3608},"error":false,"error_message":null,"status_code":null}
    
  6. OpenAI

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-openai",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":2007,"request_model":"litellm-qa-tc-openai","model_used":"gpt-5.6","tokenizer_type":"openai_api","original_response":{"object":"response.input_tokens","input_tokens":2007},"error":false,"error_message":null,"status_code":null}
    
  7. Bedrock in a region without the model

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-bedrock-unserved-region",messages:[{role:"user",content:$p}]}')"
    {"error":{"message":"{\"type\":\"error\",\"request_id\":\"req_xtf2kunfx2i7ry4od2fc4h6quzydj7u6wudlkxtdgvmimcseussa\",\"error\":{\"type\":\"not_found_error\",\"message\":\"The model 'anthropic.claude-opus-5-5' does not exist\"}}","type":"token_counting_error","param":"model","code":"404"}}
    

Gemini provider error

2 requests
  1. AI Studio with an invalid key, long prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio-invalid-key",prompt:$p}')"
    {"error":{"message":"litellm.APIError: Google Gen AI Studio API error: 400 - {\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"API key not valid. Please pass a valid API key.\",\n    \"status\": \"INVALID_ARGUMENT\",\n    \"details\": [\n      {\n        \"@type\": \"type.googleapis.com/google.rpc.ErrorInfo\",\n        \"reason\": \"API_KEY_INVALID\",\n        \"domain\": \"googleapis.com\",\n        \"metadata\": {\n          \"service\": \"generativelanguage.googleapis.com\"\n        }\n      },\n      {\n        \"@type\": \"type.googleapis.com/google.rpc.LocalizedMessage\",\n        \"locale\": \"en-US\",\n        \"message\": \"API key not valid. Please pass a valid API key.\"\n      }\n    ]\n  }\n}\n","type":"token_counting_error","param":"model","code":"400"}}
    
  2. AI Studio with an invalid key, same text as a message

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio-invalid-key",messages:[{role:"user",content:$p}]}')"
    {"error":{"message":"litellm.APIError: Google Gen AI Studio API error: 400 - {\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"API key not valid. Please pass a valid API key.\",\n    \"status\": \"INVALID_ARGUMENT\",\n    \"details\": [\n      {\n        \"@type\": \"type.googleapis.com/google.rpc.ErrorInfo\",\n        \"reason\": \"API_KEY_INVALID\",\n        \"domain\": \"googleapis.com\",\n        \"metadata\": {\n          \"service\": \"generativelanguage.googleapis.com\"\n        }\n      },\n      {\n        \"@type\": \"type.googleapis.com/google.rpc.LocalizedMessage\",\n        \"locale\": \"en-US\",\n        \"message\": \"API key not valid. Please pass a valid API key.\"\n      }\n    ]\n  }\n}\n","type":"token_counting_error","param":"model","code":"400"}}
    

Short and empty prompts

4 requests
  1. AI Studio, prompt "hi"

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:"hi"}')"
    {"total_tokens":32,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":32,"promptTokensDetails":[{"modality":"TEXT","tokenCount":32}]},"error":false,"error_message":null,"status_code":null}
    
  2. Vertex AI, prompt "hi"

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-vertex",prompt:"hi"}')"
    {"total_tokens":1,"request_model":"litellm-qa-tc-vertex","model_used":"gemini-4-argon","tokenizer_type":"gemini","original_response":{"totalTokens":1,"totalBillableCharacters":2,"promptTokensDetails":[{"modality":"TEXT","tokenCount":1}]},"error":false,"error_message":null,"status_code":null}
    
  3. AI Studio, empty prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:""}')"
    {"total_tokens":32,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":32,"promptTokensDetails":[{"modality":"TEXT","tokenCount":32}]},"error":false,"error_message":null,"status_code":null}
    
  4. Anthropic, empty prompt

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-anthropic",prompt:""}')"
    {"total_tokens":0,"request_model":"litellm-qa-tc-anthropic","model_used":"claude-opus-5-5","tokenizer_type":"huggingface_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    

Prompt next to a conversation

6 requests
  1. AI Studio, "hi" next to long messages

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:"hi",messages:[{role:"user",content:$p}]}')"
    {"error":{"message":"prompt cannot be sent with messages or contents. Set drop_params to count them without the prompt","type":"invalid_request_error","param":"prompt","code":"400"}}
    
  2. AI Studio, "hi" next to long messages, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:"hi",messages:[{role:"user",content:$p}]}')"
    {"error":{"message":"prompt cannot be sent with messages or contents. Set drop_params to count them without the prompt","type":"invalid_request_error","param":"prompt","code":"400"}}
    
  3. AI Studio, "hi" next to long contents

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:"hi",contents:[{role:"user",parts:[{text:$p}]}]}')"
    {"error":{"message":"prompt cannot be sent with messages or contents. Set drop_params to count them without the prompt","type":"invalid_request_error","param":"prompt","code":"400"}}
    
  4. AI Studio, "hi" next to long contents, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:"hi",contents:[{role:"user",parts:[{text:$p}]}]}')"
    {"error":{"message":"prompt cannot be sent with messages or contents. Set drop_params to count them without the prompt","type":"invalid_request_error","param":"prompt","code":"400"}}
    
  5. AI Studio with drop_params, "hi" next to long messages

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio-drop-params",prompt:"hi",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":2032,"request_model":"litellm-qa-tc-aistudio-drop-params","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":2032,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2032}]},"error":false,"error_message":null,"status_code":null}
    
  6. AI Studio with drop_params, "hi" next to long messages, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio-drop-params",prompt:"hi",messages:[{role:"user",content:$p}]}')"
    {"total_tokens":2016,"request_model":"litellm-qa-tc-aistudio-drop-params","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    

Prompt next to system or tools

5 requests
  1. AI Studio, long prompt next to a short system

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p,system:"You are a helpful assistant."}')"
    {"total_tokens":2043,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":2043,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2043}]},"error":false,"error_message":null,"status_code":null}
    
  2. AI Studio, long prompt next to a long system, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p,system:$p}')"
    {"total_tokens":4029,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  3. AI Studio, same text as a message next to that system, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",messages:[{role:"user",content:$p}],system:$p}')"
    {"total_tokens":4029,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  4. AI Studio, long prompt next to a tool, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p,tools:[{type:"function",function:{name:"get_weather",description:"Get the current weather for a city",parameters:{type:"object",properties:{city:{type:"string"}},required:["city"]}}}]}')"
    {"total_tokens":2056,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  5. AI Studio, same text as a message next to that tool, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",messages:[{role:"user",content:$p}],tools:[{type:"function",function:{name:"get_weather",description:"Get the current weather for a city",parameters:{type:"object",properties:{city:{type:"string"}},required:["city"]}}}]}')"
    {"total_tokens":2056,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    

Prompt next to an empty list

5 requests
  1. AI Studio, long prompt next to empty messages

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p,messages:[]}')"
    {"total_tokens":2032,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":2032,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2032}]},"error":false,"error_message":null,"status_code":null}
    
  2. Vertex AI, long prompt next to empty messages

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-vertex",prompt:$p,messages:[]}')"
    {"total_tokens":2001,"request_model":"litellm-qa-tc-vertex","model_used":"gemini-4-argon","tokenizer_type":"gemini","original_response":{"totalTokens":2001,"totalBillableCharacters":7200,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2001}]},"error":false,"error_message":null,"status_code":null}
    
  3. AI Studio, long prompt next to empty contents

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p,contents:[]}')"
    {"total_tokens":2032,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"","original_response":{"totalTokens":2032,"promptTokensDetails":[{"modality":"TEXT","tokenCount":2032}]},"error":false,"error_message":null,"status_code":null}
    
  4. Anthropic, long prompt next to empty messages

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=true" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-anthropic",prompt:$p,messages:[]}')"
    {"total_tokens":2001,"request_model":"litellm-qa-tc-anthropic","model_used":"claude-opus-5-5","tokenizer_type":"huggingface_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    
  5. AI Studio, long prompt next to empty messages, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p,messages:[]}')"
    {"total_tokens":2009,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    

Without call_endpoint

1 request
  1. AI Studio, long prompt, call_endpoint=false

    $ curl -s -X POST "http://127.0.0.1:$PORT/utils/token_counter?call_endpoint=false" -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d "$(jq -nc --rawfile p long.txt '{model:"litellm-qa-tc-aistudio",prompt:$p}')"
    {"total_tokens":2009,"request_model":"litellm-qa-tc-aistudio","model_used":"gemini-4-argon","tokenizer_type":"openai_tokenizer","original_response":null,"error":false,"error_message":null,"status_code":null}
    

Audit and blast radius

/audit passed at 49d81ff, and aac4a81 only renames a unit test. The 11 new integration cells fail at the merge base and pass in both head runs. Matrix

Contracts
Contract Base Head
AI Studio and Vertex AI prompt-only count send the prompt " " sent prompt sent
Empty messages or contents next to a prompt " " or nothing sent prompt sent
Prompt next to a conversation, no drop_params 200 or 500 400, no upstream call
Deployment drop_params, local count 500 conversation counted
Local prompt with system or tools ignored them counted like messages
Global drop_params, empty prompt, other providers unit and live unchanged
/v1/messages/count_tokens, :countTokens, /v1/responses/input_tokens 156 wire controls 152 pass, 3 existing skips, 1 inherited flake

/live-pr-risk at 3e8d052 found no unintended change, and the three internal count routes send the same wire on both sides. Report

Type

🐛 Bug Fix

Caveats (if any)

Severe

  • A prompt next to a non-empty messages or contents now answers 400 without drop_params
    • With call_endpoint=true it answered 200 before and counted only the conversation
    • It follows the repo's drop_params rule, so it is accepted

Medium

Low

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
  • 49d81ff passes /audit
  • 3e8d052 passes /live-pr-risk
Bugbot summary

[!NOTE]
Medium Risk
Changes request validation and provider routing for a widely used utility endpoint, including a breaking 400 for prompt mixed with messages/contents without drop_params.

Overview
Fixes /utils/token_counter so prompt-only requests with call_endpoint=true on Gemini and Vertex AI reach the provider count API as a single user message, matching the same text sent as messages instead of returning a bogus fixed token count.

Breaking: Sending prompt together with non-empty messages or contents now returns 400 (param: prompt) unless drop_params is set (global or on the deployment), in which case only the conversation is counted. Empty messages/contents still count as prompt-only.

On the local tokenizer path, a prompt with system or tools is counted like messages + those fields (not text= only), fixing prior 500s and under-counts. Other providers with call_endpoint=true still use local counting for prompt-only requests.

Reviewed by Cursor Bugbot for commit aac4a81. Bugbot is set up for automated code reviews on this repo. Configure here.

@codspeed

codspeed Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_fix_token_counter_prompt_only_provider_count (aac4a81) with main (642a2ad)

Open in CodSpeed

@codecov

codecov Bot commented Oct 16, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

The title uses fix(proxy)!:, and the description explains the one breaking change: prompt sent with a non-empty messages or contents now returns 400 unless drop_params is set.

Checks and execution details
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The only product file in this PR is litellm/proxy/proxy_server.py (count_request_tokens). It sits outside litellm/llms/** and litellm/litellm_core_utils/prompt_templates/**. The other changed files are tests.
  • Passed · Changed integration contracts (providers group) (optional): I ran python tests/integration/run.py providers tests/integration/providers/test_vertex_gemini_count_tokens_wire.py --workers 2 against a local Postgres and Redis, after running python -m prisma generate. Result: 34 passed in 39.32s. That includes all 13 new cases: prompt-only on Vertex and AI Studio, empty messages and empty contents, the 400 when prompt comes with messages or contents (no upstream call), drop_params on the provider and local paths, and the local count of system and tools. These cases run a real gateway against a local Gemini protocol peer.
  • Passed · Unit tests for token counter (optional): pytest tests/unit/proxy/test_proxy_token_counter.py tests/unit/proxy/proxy_server/test_routes_utils.py -n 8: 58 passed.
  • Passed · Internal callers of count_request_tokens (optional): /v1/messages/count_tokens (anthropic_endpoints/endpoints.py:350), Google :countTokens (google_endpoints/endpoints.py:88) and /v1/responses/input_tokens (response_api_endpoints/endpoints.py:1476) all build a TokenCountRequest without prompt. The new 400 guard and the prompt-to-message path cannot fire on those routes.
  • Passed · Breaking-change marker (optional): The PR changes public behavior: prompt with a non-empty messages or contents now returns 400 unless drop_params is set. The title includes !, and the description gives the impact and the migration (remove prompt or set drop_params).

View review · Reviewed aac4a81de8ae

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with the previous finding fixed and no new actionable issues found

Summary

Fixes prompt-only counts on Gemini and Vertex AI when call_endpoint=true. Mixed prompts and conversations now require drop_params, and local counts include system and tools with the prompt

The latest commit removes the previously flagged docstring and renames its test. No new issues were found

mateo-berri accepted the Vertex test’s class patch because the unchanged handler builds authentication and its HTTP client internally. Greptile accepted that explanation

  • Gemini and Vertex AI count prompt-only requests as user messages.
  • The token counter rejects prompts mixed with conversations unless drop_params is on.
  • Local counts include system instructions and tools beside a prompt.

Reviews (6) · Last reviewed commit: "test(proxy): name the token counter fall..." · Reviewed by Greptile

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

…n unless drop_params is set

With drop_params the conversation is counted without the prompt. On the local count, a prompt sent with system or tools is counted as a user message with them, like the messages form.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri mateo-berri changed the title fix(proxy): count prompt-only token_counter requests with the provider when call_endpoint is set fix(proxy)!: count prompt-only token_counter requests with the provider when call_endpoint is set Oct 16, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread litellm/proxy/proxy_server.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit aac4a81. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@litellm-stampbot

litellm-stampbot Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

litellm-stampbot: risk low

Approved at aac4a81.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Judge (gpt-6-luna): low, probability of high 0.08 (high at or above 0.75)

  • risk: low (probability of high 0.08)

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@litellm-stampbot litellm-stampbot Bot added the risk:low Small, isolated, low-risk change label Oct 16, 2026

@kerry-berri kerry-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low risk by rule and by judgement at aac4a81

@mateo-berri
mateo-berri merged commit 2dc6aaf into main Oct 16, 2026
109 of 110 checks passed
@mateo-berri
mateo-berri deleted the litellm_fix_token_counter_prompt_only_provider_count branch October 16, 2026 10:54
yuneng-berri added a commit that referenced this pull request Oct 18, 2026
…46839, #46843, #46583, #47057, #47064, #47163, #46777) (#47209)

* fix(proxy)!: count prompt-only token_counter requests with the provider when call_endpoint is set (#46839)

* fix(proxy): count prompt-only token_counter requests with the provider when call_endpoint is set

* fix(proxy): keep the local count for a prompt-only token_counter request when the provider count fails

* fix(proxy): log a prompt-only token count fallback as a one-line warning

* fix(proxy): send a prompt-only token_counter request to the provider only on Gemini and Vertex AI

* fix(proxy): count a token_counter prompt sent next to an empty messages or contents list

* fix(proxy): count a prompt next to messages on the local token count instead of answering 500

* fix(proxy): answer 400 for a token count prompt next to a conversation unless drop_params is set

With drop_params the conversation is counted without the prompt. On the local count, a prompt sent with system or tools is counted as a user message with them, like the messages form.

* test(proxy): count tools with a prompt in the token counter fallback test

* test(proxy): cover prompt counting on /utils/token_counter in the Gemini count wire tests

* test(proxy): name the token counter fallback test by what it checks

(cherry picked from commit 2dc6aaf)

* fix(count_tokens): apply context_management edits in the Gemini /v1/messages/count_tokens count (#46843)

* fix(count_tokens): apply context_management edits in the Gemini /v1/messages/count_tokens count

/v1/messages runs clear_tool_uses context edits before it sends an Anthropic
body to a Gemini or Vertex AI deployment, but /v1/messages/count_tokens counted
the body unedited, so a request with older tool results cleared counted about
2.8x what inference bills.

The count now runs the same history and context-edit step inference runs,
honors additional_drop_params on the deployment, and skips compact edits so a
count never makes a paid summary call.

* fix(count_tokens): match the Gemini count to inference for compact edits and drop opt-outs

Run compact edits in the count without the summary call so trigger checks and
history slicing match /v1/messages, honor a request-level additional_drop_params,
keep the full body when any deployment in the model group drops context_management,
and answer 400 naming a block Gemini cannot count when an edit trigger fails on it

* fix(count_tokens): count the unedited body when an edit fails and honor deployment ids in the drop check

* fix(count_tokens): log a failed edit in the count at debug, since the send already logs it

* fix(count_tokens): resolve a deployment id before wildcard routes in the drop check, as the router does

* fix(count_tokens): honor the router-wide additional_drop_params opt-out in the drop check

The router merges default_litellm_params between the deployment and the request, so a router-wide context_management opt-out makes /v1/messages send the full history. The count now reads it in the same order. Adds the audit's wire tests for the count's context edits.

* fix(count_tokens): read the opt-out of a deployment the router serves by its litellm model name

* fix(count_tokens): read the opt-out and drop_params from the deployments the router and completion_model send to

* fix(messages): drop an invalid context_management spec under drop_params so the send matches the count

* fix(count_tokens): give Claude Code and Codex counts the drop_params default /v1/messages gives them

The proxy turns on drop_params for Claude Code and Codex user agents on /v1/messages. The count now applies the same default, so an invalid context_management spec drops on both endpoints instead of the count answering 400 while the send answers 200. The wire test also covers default_fallbacks, model_group_alias, and completion_model routes.

* test(count_tokens): cover a coding agent that turns drop_params off and stop two count tests running as Claude Code

(cherry picked from commit f8217d2)

* fix(proxy)!: answer 400 for malformed tools on count_tokens instead of crashing (#46583)

* fix(proxy): answer 400 for malformed tools on count_tokens instead of crashing

A non-list tools value crashed the vector store lookup during auth and the
built-in tool cost lookup in the failure logging path, so the proxy answered
an unhandled 500 and closed the keep-alive connection. count_tokens now
answers a 400 invalid_request_error for a malformed body, drops malformed
tools when drop_params is on, and both lookups skip values of the wrong shape.

* fix(proxy): skip non-list tools in the tool allowlist check

Also validate the count_tokens body without recursion, which the recursion detector rejects.

* test(integration): restore the int tools case on count_tokens

The proxy now answers a non-list tools value with a 400, so the case is deterministic again.

* fix(proxy): reject malformed tools at the LLM route entry and keep vector store checks on malformed ids

* fix(proxy): apply drop_params like core when dropping malformed tools, and reject malformed tool vector store ids

Check tools after request setup so the Claude Code default and the logged call type apply, read the request,
global, and model group drop_params the way core does, drop tool_choice and friends with tools, cover Gemini
generateContent, and answer 400 for a malformed tools[].vector_store_ids with the strict flag off

* fix(proxy): keep the request's call type when logging a gate rejection after request setup

The body-shape fallback relabeled a /v1/messages rejection as acompletion and a list-input /v1/responses
rejection as aembedding, so it now only applies when the logging object carries no known call type

* fix(proxy): share the malformed tools check across tool routes and honor drop_params per entry

* fix(proxy): accept null vector_store_ids, read every named store id in auth, check the responses websocket

* refactor(proxy): leave the responses websocket out of the request-level tool check

* fix(proxy): let a request's additional_drop_params replace the deployment list and keep compact's call type on rejections

* fix(proxy): read router default drop lists and deployment ids in the malformed tools check

* fix(proxy): leave malformed tools to the router when it can pick another deployment

Fallbacks, auto-routers, model strings, comma batches and team model names
let the router pick a deployment after the proxy checks the request, so the
proxy now forwards a malformed tools field there as main does, and only
rejects it when the deployment it checks is the one that serves. Token
counting never reroutes, so count_tokens and input_tokens keep reading the
group they count with. additional_drop_params names are read the way core
reads them, so a list with a non-string entry still names its strings.

* test(integration): cover malformed tools on reroutable models, router defaults and deployment ids

* fix(proxy): resolve malformed tools at the deployment the router picks

* fix(proxy): keep provider-repaired tool schemas, honor fallback_on_unsupported_params, skip cooldown on malformed tools

Empty schemas and JSON-string schemas pass the tools check the way litellm's provider paths already read them. The rejection is a BadRequestError subclass carrying the deployment's provider, so fallback_on_unsupported_params: false keeps the 400, and the router never cools a deployment down for a request litellm rejected before calling it. Adds the audit's pre_call guardrail and cross-provider bridge cells.

* test(integration): expect a 400 for an empty-string tools field on /v1/messages

Real Anthropic rejects tools "" with a 400 on main too, so the case joins the malformed tools test

* fix(router): keep web search routing for tools passed as a tuple

* fix(router): keep a deployment's own tools when drop_params drops a malformed request tools

* test(router): list _merged_tools as covered through the deployment tools merge tests

* fix(router): drop the request's tool settings with its malformed tools when deployment tools replace them

* fix(router): skip a tool whose type is not a string in the web search filter instead of raising TypeError

* fix(prometheus): keep deployment health metrics clean on a malformed tools rejection

* test: type the new malformed tools tests

* test: mark new test locals Final and type kwargs dicts

(cherry picked from commit d76ec3a)

* ci(cost map): classify token_count_model as an object key in the schema generator (#47057)

* ci(cost map): classify token_count_model as an object key in the schema generator

* ci(cost map): require non-blank token_count_model strings and test the region rules

(cherry picked from commit 6e191a5)

* ci(cost map): remove the generated model prices JSON schema (#47064)

* ci(cost map): remove the generated model prices JSON schema

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(cost map): keep schema-independent cost map tests after dropping the schema

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* ci(cost map): keep the schema file until main's guard stops requiring it

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* ci(cost map): let bot sync PRs keep touching the schema file until it is deleted

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit ae6f7f6)

* fix(count_tokens)!: answer 400 for Vertex partner models without a count API and OpenAI-shaped provider errors on /v1/responses/input_tokens (#47163)

* fix(count_tokens): answer 400 for Vertex partner models without a count API and OpenAI-shaped provider errors on /v1/responses/input_tokens

* fix(count_tokens): answer 400 for Vertex Mistral counts and type the input_tokens error tests

Vertex has no count-tokens route for Mistral or codestral models, so they now
get the same 400 as other partner models without a count API instead of a 404
that points operators at IAM.

* fix(count_tokens): unwrap prefixed provider errors on /v1/responses/input_tokens

* fix(count_tokens): say LiteLLM, not Vertex, cannot count a Vertex partner model

* fix(count_tokens): count a Vertex partner model with its configured custom_tokenizer and unwrap prefixed flat provider errors

* fix(count_tokens): keep the 400 for contents-only Vertex partner counts with a custom_tokenizer

* fix(count_tokens): pass through an OpenAI provider error that omits param or code

* fix(count_tokens): keep the status-based type for Anthropic count errors on the Responses route

* test(count_tokens): cover the Vertex partner count gate and Responses count error shapes on a real proxy

* test(count_tokens): add regression tests for the Vertex partner count gate and Responses count error shapes

(cherry picked from commit ef1d395)

* feat(count_tokens)!: configurable token_count_framing and token_count_model, count source in the response (#46777)

* feat(count_tokens): configurable token_count_framing and token_count_fallback_model, count source in the response

Count endpoints now say where each number came from in litellm_count_source
(provider, fallback_model, local_estimate) and name the fallback model in
litellm_count_fallback_model. When the provider answers 400 or 404 for a model
it cannot count, the proxy counts the same request with token_count_fallback_model.
token_count_framing adds a per-model constant to local estimates. Both settings
ship in the cost map for Bedrock Claude Sonnet/Haiku 5.5, Bedrock Kimi K3, and
Databricks Kimi K3 and DeepSeek V4 Flash, and can be overridden in model_info.

* test(count_tokens): classify the new cost map keys in the schema generator and expect count_source in exact-shape tests

* test(count_tokens): e2e matrix against real inference and integration wire tests for count source, fallback and framing

* fix(count_tokens): keep the provider error when local counting is disabled, name the fallback error, keep settings in cooldown

Moves the cost map lookup off the event loop

* ci(cost map): bound token_count_framing to non-negative and token_count_fallback_model to non-empty

* fix(count_tokens): keep a failed fallback's own status, ship fallbacks only where they count, add system.ai framing

A fallback model that answers 404 returns the requested model's error unchanged, and any other fallback
failure answers with its own status and message. The eu, apac, au and jp Sonnet and Haiku 5.5 entries
no longer ship the Opus 5.5 fallback, which AWS serves only in us-east-1. A configured empty
token_count_fallback_model turns the shipped fallback off. Config framing accepts whole-number floats and
rejects negatives. The Databricks system.ai Kimi K3 and DeepSeek V4 Flash names carry the same framing as
their serving endpoint names, and the e2e matrix runs on Bedrock Haiku 5.5 too.

* test(databricks): list the system.ai Kimi K3 and DeepSeek V4 Flash names with their published DBU rates

* fix(count_tokens): skip a token count fallback model for an hour after it answers 404 on that deployment

A us. or global. Sonnet 5.5 deployment outside us-east-1 paid two extra Bedrock
calls and about 200 ms on every count, since Opus 5.5 cannot count there either.
The Kimi K3 e2e also runs the large system prompt shape now.

* test(count_tokens): use the shared integration port allocator in the fallback wire test

* fix(cost map): keep the Databricks system.ai entries to framing only, so their spend stays as today

* test(count_tokens): cover the fallback 404 skip, inference profile base_model, shipped framing, and deployment-scoped token count settings

Adds integration cells for a fallback model that answers 404, an application inference profile ARN deployment whose base_model carries the shipped fallback, and the shipped Kimi K3 framing with token_count_framing 0 turning it off. Adds unit tests that keep token count settings off the shared backend cost map key and that store a token count setting on PATCH only when the operator changed it

* fix(count_tokens): keep the counter's own 400 and the provider's error when a framed estimate cannot read the body

A 400 the OpenAI or Gemini counter returns before calling the provider is the caller's answer, so it no longer tries the fallback model or a framed estimate. When the framed local estimate cannot read a content block, the client gets the provider's error instead of a 500. Adds /audit round 2's integration tests for the fallback leg's converted body, the Anthropic envelope on fallback failures, and both framing cases.

* fix(count_tokens): answer the provider's error whenever a framed estimate raises

A tool schema the local estimate cannot format, such as a boolean subschema or an array with no items, raised AttributeError or KeyError and answered a 500 on a framed deployment whose provider had already answered 400. Any estimate failure now answers the provider's own error.

* fix(count_tokens): load the custom tokenizer inside the guarded framed estimate

A framed deployment whose custom_tokenizer could not load answered a 500 or 503 where the provider had already answered 400, because the tokenizer was selected outside the estimate's error handling. Selecting it inside answers the provider's error, logs a warning with the estimate's error, and still raises the Rust extension's fork-guard errors.

* fix(count_tokens): look up framing under the deployment's custom_llm_provider

* fix(count_tokens): share one tokenizer download per worker and bound the wait after a provider error

A framed deployment whose custom_tokenizer is not cached locally made every
count wait out the Hugging Face hub's whole retry cycle when the hub could not
be reached, and a burst of those loads held the default thread limiter that
every count's cost map lookup also needs. Counts on a worker now share one
download per minute, a failed download is reused for the rest of that minute,
and after a provider error a count waits at most 5 s before answering the
provider's error. The swallowed-estimate warning logs only the error type.

* fix(count_tokens): keep one tokenizer download per key running and load the local route per request

* test(count_tokens): type the scripted counter and wait on events instead of wall time where possible

* fix(count_tokens): run framed tokenizer loads on their own capped threads and answer a tokenizer panic with the provider error

Framed loads used anyio's default 40 threads, so a hub that drops packets let about 40 hanging loads stall every count on the worker. Loads now run on a per-worker pool of 4, and a count that finds 4 loads running answers the provider's error at once. Any finished load is reused for a minute after it finishes, so a load that fell back to tiktoken is not retried on every count. A pyo3 PanicException from the tokenizer, while loading or counting, now answers the provider's error instead of a plain 500

* feat(proxy): count tokens with token_count_model in its pinned region

token_count_model {model, region} replaces token_count_fallback_model. Bedrock Sonnet and Haiku 5.5 count with Opus 5.5 in us-east-1, or Melbourne for au. profiles, and a failure names the region to enable

* fix(count_tokens): use the renamed count model constant in the e2e test and list token_count_model with the object keys

* fix(proxy): keep the upstream error envelope when adding the region hint

* test(proxy): annotate the token count setting echo test

* ci(cost map): require non-blank token_count_model strings and test the region rules

* fix(count_tokens): answer the token_count_model's error even when framing is set

* fix(count_tokens): keep the provider error for Google contents instead of a framed estimate

* fix(count_tokens): estimate Google contents the route translated to messages

* fix(count_tokens): keep the provider error for Google contents with non-text parts

* test(proxy): drive tokenizer wait and cost map tests by events and a skippable loop clock

* fix(count_tokens): check Google text-only parts without a KeysView comparison basedpyright flags

* feat(proxy): count Bedrock Kimi K3 tokens exactly with its pinned tokenizer

* test(bedrock): keep the Kimi K3 image check in-process

* fix(count_tokens): join the region hint to an upstream message that already ends with a period

Also pins that a blank token_count_model in config falls through to the cost map default

* fix(count_tokens): count Gemini tool-call turns and Responses tools, and stop tokenizer retries from stalling counts

The Google countTokens route estimates contents with functionCall, functionResponse and thoughtSignature parts again, and still answers the provider error for media, thought and unknown parts

The Kimi K3 exact count renders Responses API and Anthropic tools through the chat tool translation the Vertex count already used, now shared from the prompt factory, and falls back to the estimate when the Converse body cannot carry a tool

A failed Kimi K3 tokenizer load is retried in the background without making counts wait, and a load still running after the wait logs a warning

* fix(count_tokens): count Kimi K3 tools the way Bedrock inference sends them

A flat Responses API function or custom tool becomes the chat tool the
Responses route sends to inference, and every other tool goes to the
Converse body as is, so hosted tools Bedrock drops are left out of the
count instead of being counted or turning it into an estimate.

* test(count_tokens): annotate new token counter test locals with Final

* fix(count_tokens): keep shipped count regions inside the deployment's geography

A plain Bedrock Sonnet or Haiku 5.5 deployment in a non-US region no longer sends its count prompt to us-east-1. Global count models and configured token_count_model keep their pinned region. Also expect litellm_count_source in the Vertex Llama count test main added

* fix(count_tokens): resolve count settings off the event loop

(cherry picked from commit 75faaea)

---------

Co-authored-by: Mateo Wang <277851410+mateo-berri@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
mateo-berri added a commit that referenced this pull request Oct 19, 2026
Preserve the prompt normalization required by #46777 from #46839 and classify its token_count_tokenizer key using the upstream schema definition.

This branch was successfully deployed

No deployments
e2e-changed — aac4a81d Deployed Oct 16, 2026 by mateo-berri via oauth #5546
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Small, isolated, low-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants